package com.wxx.util;

import com.wxx.util.exception.IExceptionHandler;

import java.util.ArrayList;
import java.util.List;

public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static MyExceptionHandler exceptionHandler = null;
    private List<IExceptionHandler> callbackList;

    public static MyExceptionHandler getInstance() {
        if (exceptionHandler == null){
            synchronized (MyExceptionHandler.class){
                if (exceptionHandler == null){
                    exceptionHandler = new MyExceptionHandler();
                }
            }
        }
        return  exceptionHandler;
    }

    public void setDefaultUnCacheExceptionHandler(){
        Thread.setDefaultUncaughtExceptionHandler(this); //设置应用默认的全局捕获异常器
    }

    public void addExceptionListener(IExceptionHandler listener) {
        if (listener == null) {
            return;
        }
        if (callbackList == null) {
            callbackList = new ArrayList<>();
        }
        callbackList.add(listener);
    }

    public void removeExceptionListener(IExceptionHandler listener) {
        if (listener == null || callbackList == null) {
            return;
        }
        callbackList.remove(listener);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
//        System.out.println("收集到了异常:" + thread.getName() + "  " + throwable.getMessage());
        if (callbackList == null || callbackList.isEmpty()) {
            return;
        }
        for (IExceptionHandler listener: callbackList) {
            listener.handler(thread, throwable);
        }
    }

}